package org.torproject.android;

import java.util.List;

import java.util.Timer;
import java.util.TimerTask;

import org.torproject.android.service.ITorService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.webkit.WebView;

public class BandwidthView extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Debug.startMethodTracing("BandwidthView");
		
		setContentView(R.layout.layout_bandwidth);
		webView = (WebView) findViewById(R.id.bandwidthWebView);
		
		mConnection = new ITorServiceConnection();
		bindService();
		

		getInfoTask = new GetInfoTask();
    	timerTask = new TimerTask() {

			@Override
			public void run() {
				Log.i("TOR_SERVICE", "running time task");
				new GetInfoTask().execute("circuit-status");
			}
    	};	
    	
		timer = new Timer(true);

    	mHandler = new Handler() {
    		@Override
    		public void handleMessage(Message message) {
    			webView.loadUrl(url);
    		}
    	};
	}
	
	@Override
	public void onStop() {
		super.onStop();
		Debug.stopMethodTracing();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
		timer.cancel();
	}
	
    private void bindService ()
    {
    	 bindService(new Intent(ITorService.class.getName()),
                 mConnection, Context.BIND_AUTO_CREATE);    	 
    }
        
    private class ITorServiceConnection implements ServiceConnection {

    	public void onServiceConnected(ComponentName className, IBinder service) {
        	mService = ITorService.Stub.asInterface(service);
        	timer.schedule(timerTask, 0, 10000);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
        }
    };

    private class GetInfoTask extends AsyncTask<String, Integer, List<BandwidthData>> {
        
    	@Override
    	protected List<BandwidthData> doInBackground(String... urls) {
            try {
				return mService.getBandwidthUsage();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			return null;
        }

    	@Override
        protected void onPostExecute(List<BandwidthData> result) {
    		StringBuffer read = new StringBuffer();
    		StringBuffer write = new StringBuffer();
    		
    		long max = 0;
    		for(BandwidthData data : result) {
    			if(read.length() > 0) {
    				read.append(",");
    			}
    			if (data.read > max) {
    				max = data.read;
    			}
    			read.append(data.read);
    			
    			if(write.length() > 0) {
    				write.append(",");
    			}
    			
    			if(data.write > max) {
    				max = data.write;
    			}
    			write.append(data.write);
    		}
    		
    		Log.i("TOR_SERVICE", "Read: " + read.toString());
    		Log.i("TOR_SERVICE", "Write: " + write.toString());
    		
    		url = "http://chart.apis.google.com/chart" +
    		"?chxr=0,0,"+ max * 2 +
    		"&chxs=0,676767,10.5,0,l,676767" +
    		"&chxt=y" +
    		"&chs=300x365" +
    		"&cht=lc" +
    		"&chco=3D7930,FF9900" +
    		"&chd=t:" + read.toString() + "|" + write.toString() +
       		"&chg=14.3,-1,1,1" +
    		"&chls=2,4,0|1" +
    		"&chma=20" +
    		"&chdl=KB+Read|KB+Written";

    		mHandler.sendEmptyMessage(0);
		}
    }
 
    String url;
    Handler mHandler;
    Timer timer;
    WebView webView;
    GetInfoTask getInfoTask;
    TimerTask timerTask;
    ITorService mService;
    ITorServiceConnection mConnection;
}
